#include "runMorphOp.h"

gboolean runMorphOp(gboolean imageIsSelected, Image *imageSelected, GtkWidget *widget2cann, EEType type, char *op) {

	Image *img;
	pixel **Matrix;
	EE ee;
	int width, height, rowstride, n_channels, i, j;
	GdkPixbuf *gdkPixbuf;
	guchar *p, *pixels;

	if (imageIsSelected == TRUE) {
		setMatrix(&ee, type);

		img	= buildImageMatrix(getImageHeight(imageSelected), getImageWidth(imageSelected));

		Matrix= (pixel**)malloc(getImageHeight(imageSelected) * sizeof(pixel*));
		for (i = 0; i < getImageHeight(img); i++) {
			Matrix[i] = (pixel*)malloc(getImageWidth(imageSelected)
					* sizeof(pixel));
		}

		if (strcmp(op, "erode")) {
			Matrix = erode(imageSelected->Matrix, &ee, getImageHeight(imageSelected), getImageWidth(imageSelected), 3, 3);
		} else if (strcmp(op, "dilate")){
			Matrix = dilate(imageSelected->Matrix, &ee, getImageHeight(imageSelected), getImageWidth(imageSelected), 3, 3);
		} else {
			printf("É necessário escolher uma operação\n");exit(1);
			exit(0);
		}
		
		img->Matrix = Matrix;
		gtk_label_set_text(GTK_LABEL(lookup_widget(widget2cann, "_2cann_label_image")), "Eroded Image");
		gdkPixbuf = gtk_image_get_pixbuf(GTK_IMAGE(lookup_widget(widget2cann, "image1")));
		n_channels = gdk_pixbuf_get_n_channels (gdkPixbuf);

		g_assert (gdk_pixbuf_get_colorspace (gdkPixbuf) == GDK_COLORSPACE_RGB);
		g_assert (gdk_pixbuf_get_bits_per_sample (gdkPixbuf) == 8);

		width = gdk_pixbuf_get_width (gdkPixbuf);
		height = gdk_pixbuf_get_height (gdkPixbuf);

		rowstride = gdk_pixbuf_get_rowstride (gdkPixbuf);
		pixels = gdk_pixbuf_get_pixels (gdkPixbuf);

		for (i = 0; i < height; i++) {
			for (j = 0; j < width; j++) {
				p = pixels + i * rowstride + j * n_channels;
				p[0] = p[1] = p[2] = img->Matrix[i][j];
			}
		}
		gtk_image_set_from_pixbuf(GTK_IMAGE(lookup_widget(widget2cann, "image1")), gdkPixbuf);

		return TRUE;

	} else {
		return FALSE;
	}
}
